/**
 * @author GodSon
 * http://www.btboys.com
 * date 2011-4-17 21:30
 */
document.onselectstart=function(e){
    return false
    }

//注册命名空间
GNamespace.register("OS.Init");

/**
 *初始化app拖拽
 **/
OS.Init.appIconDrag = function (){
    $('.app').draggable({
        revert:true
    }).droppable({
        onDrop:function(e,source){
            $.data(source, 'draggable').options.revert = true;
            if($(source).prev().attr('id') == $(this).attr('id')){
                $(source).insertBefore(this);
            }else{
                $(source).insertAfter(this);
            }
            OS.Init.appReset();
        },
        onDragOver:function(e,source){
            $.data(source, 'draggable').options.revert = false;
        },
        onDragLeave:function(e,source){
            $.data(source, 'draggable').options.revert = true;
        },
        accept:'.app'
    });
}
//时间日期
OS.Init.InfoTime = function(){
    var MyDate=new Date();
    var Text=MyDate.getMonth()+"月"+MyDate.getDate()+"日 "+MyDate.toLocaleTimeString()
    $('#GD_Time').text(Text);
}
setInterval(OS.Init.InfoTime,1000);

/**
 *初始化app
 **/
OS.Init.InitApp = function(AppList){
    var ListNum=Math.floor((document.body.clientHeight-50)/90);
    var iNum=1,iList=1;
    for(var i=0;i<AppList.length;i++){
        if(iNum>ListNum){
            iNum=1;
            iList++
        }
        var T=10+90*(iNum-1);
        var L=85*iList-80;
        iNum++;
        var appId="App_"+AppList[i].id;
        var appIcon = "app-"+AppList[i].iconCls;
        var app = $("<div id='"+appId+"' style=\"top:"+T+"px;left:"+L+"px\" class='app'><div class='appIcon "+appIcon+"'></div><div class='appText'>"+AppList[i].text+"</div></div>");
        app.data("app",AppList[i]);
        bingAppEvent(app);
        $('.GD_windBody').append(app);
    }
    var f = $('<div style="float:right;"><object id="item_47960" data="sources/widget/clock1.swf" width="110" height="110" type="application/x-shockwave-flash"><param name="allowScriptAccess" value="always"><param name="allownetworking" value="all"><param name="allowFullScreen" value="true"><param name="wmode" value="transparent"><param name="scale" value="noScale"><param name="menu" value="false"></object></div>')
    f.draggable();
    $('.GD_windBody').append(f);
    OS.Init.appIconDrag();
	
    /**
	 *app的事件绑定
	 **/
    function bingAppEvent(app){
        app.dblclick(OS.Init.AppItemClik).hover(function(){
            $(this).addClass("IcoOn");
        },function(){
            $(this).removeClass("IcoOn");
        }).mousedown(function(){
            $('.app').removeClass("IcoDown");
            $(this).addClass("IcoDown");
        }).bind('contextmenu',function(e){
            $('#appContextmenu').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
            return false;
        });;
    }
}

/**
 *初始化开始菜单
 **/
OS.Init.InitStartMenu = function(Menus){
    Menus = Menus || [];
    var startMenu =$('<div id="startMenu" style="width:200px;"></div>').appendTo('body');
    for(var i=0;i<Menus.length;i++){
        if(Menus[i].children){
            startMenu.append(appendChild(Menus[i].text,Menus[i].children));
        }else{
            var item = $('<div></div>').html(Menus[i].text).attr("url",Menus[i].href).click(OS.Init.AppItemClik).data("app",Menus[i]);
            startMenu.append(item);
        }
    }
    startMenu.menu();
    startMenu.menu("appendItem",{
        text:"退出",
        onclick:"OS.Init.logout()"
    });
	
    function appendChild(itemText,childrens){
        var item = $('<div></div>').append($('<span></span>').html(itemText));
        var ci = $('<div style="width:200px;"></div>');
		
        for(var i=0;i<childrens.length;i++){				
            if(childrens[i].children){
                item.append(ci.append(appendChild(childrens[i].text,childrens[i].children)));
            }else{
                item.append(ci.append($('<div></div>').html(childrens[i].text).attr("url",childrens[i].href).click(OS.Init.AppItemClik).data("app",Menus[i])));
            }
        }
        return item;
    }
	
    $("#KsMenu").click(function(){
        $('#startMenu').menu('show',{
            left:0,
            top:$('.GD_windBody').height()-$('#startMenu').height()-6
        });
    });
	
}
/**
 *重置app位置
 **/
OS.Init.appReset=function(){
    var W=document.body.clientWidth-200;
    $("#GD_WinFinfo").css("width",W);
	
    var apps = $(".GD_windBody > div.app");
    var ListNum=Math.floor((document.body.clientHeight-50)/90);
    var iNum=1,iList=1;
    for(var i=0;i<apps.length;i++){
        if(iNum>ListNum){
            iNum=1;
            iList++
        }
        var T=10+90*(iNum-1);
        var L=85*iList-80;
        iNum++;
        $('.GD_windBody').append($(apps[i]).css({
            top:T,
            left:L
        }));
    }
    $('.app').removeClass("IcoOn");
    $('.app').removeClass("IcoDown");
}
/**
 *退出
 **/
OS.Init.logout = function(){
    OS.common.delCookie("osSinaapp");
    OS.Init.login ();
    $('.GD_windBody').empty();
    $('#GD_WinList').empty().css("width",0);
}
/**
 *app的双击事件
 **/
OS.Init.AppItemClik = function(){
    $(this).openApp();
    OS.Init.ChangeWList("");
}	
/**
 *改变toolbar的窗口
 **/
OS.Init.ChangeWList = function(Ctype){
    if(Ctype==""){
        var N=$("#GD_WinList").children().length;
        $("#GD_WinList").css("width",101*N);
        $("#GD_WinFinfo").scrollLeft($("#GD_WinFinfo")[0].scrollWidth);
        if($("#GD_WinFinfo")[0].clientWidth<$("#GD_WinFinfo")[0].scrollWidth){
            $("#GD_FScro").show()
            }else{
            $("#GD_FScro").hide()
            }
    }
    if(Ctype=="left"){
        $("#GD_WinFinfo")[0].scrollLeft=$("#GD_WinFinfo")[0].scrollLeft-5;
        CWlistTimer=window.setTimeout("OS.Init.ChangeWList('left')",10);
    }
    if(Ctype=="right"){
        $("#GD_WinFinfo")[0].scrollLeft=$("#GD_WinFinfo")[0].scrollLeft+5;
        CWlistTimer=window.setTimeout("OS.Init.ChangeWList('right')",10)
    }
    if(Ctype=="out"){
        clearTimeout(CWlistTimer)
        }
}
/**
 *日历
 **/
OS.Init.showCalendar = function (){
    var T = $('.GD_windBody').height() - 176;
    var L = $('.GD_windBody').width() - 178;
    $('#OS_calendar').css({
        "top":T,
        "left":L,
        "position":"absolute"
    }).slideToggle("normal");
}
/**
 *弹出登录框
 **/
OS.Init.login =function(){
    var login = {
        url:"index.php/OSLogin",
        title:"登陆",
        height:250,
        width:400,
        resizable:false,
        maximizable:false,
        minimizable:false,
        cache:false,
        draggable:false,
        closable:false,
        shadow:false,
        buttons:[{
	    id:"longin_submit",
            text:"登陆",
            handler:function(){
                OS.Init.longin_submit(GETWIN($(this)));
            }
        },{
            text:"注册",
            handler:OS.Init.register
        }],
	onComplete:function(winId){
		$("#OSLoginForm input").bind('keydown', 'return',function (evt){
			OS.Init.longin_submit(GETWIN(winId));
			return false;
		}).eq(0).focus();
	}
    };
    $.createWin(login);
}
/**
 *登陆
 **/
OS.Init.longin_submit = function(thiswin){
    if($('#OSLoginForm').form('validate')){
        //获取表单数据
        var params = $('#OSLoginForm').formJsonSerialize();
        $.ajax({
            url:"index.php/OSLogin/login",
            data:params,
            type:"POST",
			async:false,
            success:function(msg){
                if($.trim(msg) == "success"){
		    OS.common.setCookie("osSinaapp","success");
                    OS.Init.OS_init();
                    $(thiswin).destroy();
                }else{
                    OS.common.Messager("登陆失败！账号密码不匹配！");
                } 
            }
        });
    }
}
/**
 *注册
 **/
OS.Init.register = function(){
    var register = {
        url:"index.php/OSregister",
        title:"注册",
        height:320,
        width:450,
        resizable:false,
        maximizable:false,
        minimizable:false,
        cache:false,
        draggable:false,
        shadow:false,
        modal:false,
        buttons:[{
	    id:"registerBtn",	
            text:"注册",
            handler:function(){
                OS.Init.register_submit(GETWIN(this));
            }
        }],
	onComplete:function(){
		$('input[name="username"]').blur(function(){
			if($.trim($(this).val()) != ""){
				$.ajax({
					url:'index.php/OSregister/checkNameUni',
					data:'username='+$(this).val(),
					type:'POST',
					async:false,
					success:function(data){
						if(data != "true"){
							$.messager.alert("系统提示","该用户名已经存在！");
							$("#registerBtn").linkbutton("disable");
						}else{
							$("#registerBtn").linkbutton("enable");
						}
					}
				});
			}
		});
	}
    };
    $.createWin(register);
}
/**
 *注册事件
 **/
OS.Init.register_submit = function(thiswin){
    if($('#OSRegisterForm').form('validate')){
        //获取表单数据
        var params = $('#OSRegisterForm').formJsonSerialize();
        $.ajax({
            url:"index.php/OSregister/register",
            data:params,
            type:"POST",
            success:function(msg){
                if($.trim(msg) == "success"){
                    $("#OS_loginName").val(params['username']);
                    $("#OS_loginPassword").val(params['password']);
                    $(thiswin).destroy();
                }else{
                    OS.common.Messager("注册失败！");
                } 
            }
        });
    }
}
/**
 *app右键打开
 **/
OS.Init.appContextmenuOpen = function(){
    $('.GD_windBody > div.IcoDown').openApp();
    OS.Init.ChangeWList("");
}
/**
 *桌面右键属性
 **/
OS.Init.deskAtrr = function(){
	
    }
/**
 *app右键属性
 **/
OS.Init.appAtrr = function(){

    }
/**
 *OS初始化
 **/
OS.Init.OS_init = function(){
    var AppList = [{
        id:'1',
        text:'我的OS',
        iconCls:'system',
        href:'http://www.btboys.com'
    },{
        id:'11',
        text:'个人设置',
        iconCls:'person'
    },{
        id:'12',
        text:'系统配置',
        iconCls:'system-set'
    },{
        id:'7',
        text:'使用反馈',
        iconCls:'message',
	href:'index.php/FeedBack'
    }];
	
    var startMenu = [{
        id:"startMenu1",
        text:"Google",
        href:"http://www.google.com.hk"
    },{
        id:"startMenu2",
        text:"Sina",
        href:"http://www.sina.com"
    },

    {
        id:"startMenu3",
        text:"GodSon",
        href:"http://www.btboys.com"
    }];

    $('.GD_windBody').bind('contextmenu',function(e){
        $('#deskTopContextmenu').menu('show', {
            left: e.pageX,
            top: e.pageY
        });
        return false;
    });
    var W=document.body.clientWidth-200;
    $("#GD_WinFinfo").css("width",W);
    $(window).bind('resize',OS.Init.appReset);

    OS.Init.InitApp(AppList);
    OS.Init.InitStartMenu(startMenu);
}

$(function(){
    if($.browser.msie && parseInt($.browser.version) < 8){ 
        $.messager.alert("温馨提示","您当前正在使用的是IE"+$.browser.version+"。该程序支持<a style='color:green' target='_blank' href='http://windows.microsoft.com/zh-CN/internet-explorer/products/ie/home'>IE8.0</a>以上版本及谷歌，火狐..");
    }else{	
        setTimeout(function(){
            $('#GD_Loading').hide();
	if(OS.common.getCookie("osSinaapp")){
	    OS.Init.OS_init();
	}else{
	     OS.Init.login ();
	} 
        },2000)
    }
});
